package com.project.m.api.busi.handlers.hicatcard.wx;

import com.project.m.api.busi.bean.wx.pay.WxNotifyBizReq;
import com.project.m.api.busi.bean.wx.pay.WxNotifyBizResp;
import com.project.m.api.busi.db.entity.hicatcard.card.TCard;
import com.project.m.api.busi.db.entity.hicatcard.pay.TPayOrder;
import com.project.m.api.busi.db.entity.hicatcard.user.TUserCard;
import com.project.m.api.busi.db.service.hicatcard.WxTokenService;
import com.project.m.api.busi.db.service.hicatcard.card.CardService;
import com.project.m.api.busi.db.service.hicatcard.coupon.CouponService;
import com.project.m.api.busi.db.service.hicatcard.pay.PayOrderService;
import com.project.m.api.busi.db.service.hicatcard.user.UserCardService;
import com.project.m.api.busi.db.service.hicatcard.user.UserCouponService;
import com.project.m.api.busi.db.service.hicatcard.user.UserService;
import com.project.m.api.busi.util.IdGenerator.IdGenerator;
import com.project.m.api.busi.util.OrderStatus;
import com.project.m.api.busi.util.TimeUtil;
import com.project.m.api.busi.util.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

//https://mp.weixin.qq.com/debug/wxadoc/dev/api/notice.html#模版消息管理

@Component
public class NotiWxinBizHandler {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserService userService;

    @Autowired
    PayOrderService payOrderService;

    @Autowired
    UserCardService userCardService;

    @Autowired
    CardService cardService;

    @Autowired
    CouponService couponService;

    @Autowired
    UserCouponService userCouponService;

    @Autowired
    WxTokenService wxTokenService;

    @Value("${weixin.miniapp.appid}")
    String wxMinAppId;

    @Value("${weixin.miniapp.secret}")
    String wxMinAppSecret;

    @Value("${weixin.message.send.template.pay}")
    private String messageTemplate;

    public String handle(WxNotifyBizReq notiWxinBizReq, String requestBody) throws Exception {
        logger.info("notify xml = " + requestBody);
        WxNotifyBizResp resp = new WxNotifyBizResp();
        if (!notiWxinBizReq.getReturn_code().equalsIgnoreCase("SUCCESS")) {
            // TODO微信通知返回不成功
            resp.setReturn_code("FAIL");
            String xmlReq = XmlUtil.toXML(resp, WxNotifyBizResp.class);
            return xmlReq;
        }

        try {
            List<TPayOrder> payOrderList = payOrderService.findByPayOrderNumber(notiWxinBizReq.getOut_trade_no());
            if (payOrderList == null || payOrderList.size() == 0) {
                resp.setReturn_code("FAIL");
                resp.setReturn_msg("pay order list null or empty");
                String xmlReq = XmlUtil.toXML(resp, WxNotifyBizResp.class);
                return xmlReq;
            }

            TPayOrder payOrder = payOrderList.get(0);

            // 已经支付
            if (payOrder.getStatus().equalsIgnoreCase(OrderStatus.STATUS_4_DELIVERED)) {
                resp.setReturn_code("SUCCESS");
                String xmlReq = XmlUtil.toXML(resp, WxNotifyBizResp.class);
                return xmlReq;
            }

            // 卡片信息
            TCard card = cardService.findByCardId(payOrder.getCardId());
            if (card == null) {
                resp.setReturn_code("FAIL");
                resp.setReturn_msg("card is not existed");
                String xmlReq = XmlUtil.toXML(resp, WxNotifyBizResp.class);
                return xmlReq;
            }

            TUserCard userCard = new TUserCard();
            userCard.setUserId(payOrder.getUserId());
            userCard.setCardId(payOrder.getCardId());
            userCard.setUserCardNumber(IdGenerator.generateOrderId(IdGenerator.ORDERID_PREFIX_USER_CARD, "00", "0000"));
            userCard.setSource(TUserCard.SOURCE_PURCHASE);
            userCard.setSourceUserId(null);
            userCard.setStatus(TUserCard.STATUS_NOT_ACTIVE);
            userCard.setEndTime("");

            //20190104 万能卡需要有效期，其他都不用 endtime时间换成235959
            if (TCard.TYPE_MASTER.equalsIgnoreCase(card.getType())) {
                SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMdd");
                if (card.getEffectiveDay() != null) {
                    //SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    //userCard.setEndTime(outFormat.format(TimeUtil.addDateNDay(new Date(), card.getEffectiveDay())));
                    //SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMdd");
                    userCard.setEndTime(outFormat.format(TimeUtil.addDateNDay(new Date(), card.getEffectiveDay())) + "235959");
                } else {
                    //SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    //userCard.setEndTime(outFormat.format(TimeUtil.addDateNDay(new Date(), 365)));
                    userCard.setEndTime(outFormat.format(TimeUtil.addDateNDay(new Date(), 365)) + "235959");
                }
            }


            userCard.setCreateTime(TimeUtil.getCurrTime());
            userCard.setUpdateTime(TimeUtil.getCurrTime());
            userCard.setEnable(true);

            userCardService.saveUserCardByNotify(userCard, payOrder);

            resp.setReturn_code("SUCCESS");
            String xmlReq = XmlUtil.toXML(resp, WxNotifyBizResp.class);
            return xmlReq;
        } catch (Exception e) {
            resp.setReturn_code("FAIL");
            resp.setReturn_msg("inner error");
            String xmlReq = XmlUtil.toXML(resp, WxNotifyBizResp.class);
            return xmlReq;
        }

    }

}
